package com.imm.da.main.widget

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView
import com.imm.da.R

/**
 * <p>------------------------------------------------------
 * <p> Copyright (C) 2021 zhangmz, All rights reserved.
 * <p> If there is technical discussion, you can contact zhangmz90@foxmail.com
 * <p>------------------------------------------------------
 * <p> 圆角的imageview
 * <p>
 *
 * @author Created by zhangmz
 * @date on 2022/5/13
 */
class RoundImageView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyle: Int = 0
): AppCompatImageView(context, attrs, defStyle) {

    private val radius = context.resources.getDimension(R.dimen.dp_100)

    private val rect by lazy(LazyThreadSafetyMode.NONE) {
        val r = Rect().apply { getGlobalVisibleRect(this) }
        RectF(
            0f,
            0f,
            r.width().toFloat(),
            r.height().toFloat())
    }

    private val mPaint by lazy {
        Paint().apply {
            isAntiAlias = true
            color = Color.WHITE
            xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
        }
    }

    private val mPath by lazy {
        Path().apply {
            addRoundRect(rect, floatArrayOf(radius, radius, radius, radius, radius, radius, radius, radius), Path.Direction.CW)
        }
    }

    override fun onDraw(canvas: Canvas) {
        canvas?.run {
            runCatching {
                clipPath(mPath)
                drawPath(mPath, mPaint)
                super.onDraw(canvas)
            }.getOrElse {
                super.onDraw(canvas)
            }
        }?: super.onDraw(canvas)
    }

}